package cn.findviewbydream.evil.main.task;

import cn.findviewbydream.evil.app.websocket.WebSocketHandlerImpl;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

/********************************************
 * 工程名：MealOrder
 * 包名：cn.findviewbydream.evil.main.task
 * 时间：17-2-7
 * 作者：白雨濃 evil
 * 邮箱：evilbai@foxmail.com
 * 内容：
 ********************************************/
public class AutoRunTask
{
    /**
     * 长连接的心跳，20s一次
     */
    public void heartBeat()
    {
        WebSocketHandlerImpl.Companion.sendMessageToUsers("1");
    }

    public void backupDataBase()
    {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

        try
        {
            String name = format.format(new Date());
            String filePath = System.getProperty("root.path") + "WEB-INF/backup/";

            File file = new File(filePath);

            boolean isMkdir = false;

            if (!file.exists())
                isMkdir = file.mkdir();
            System.out.println(isMkdir);

            filePath += name + ".sql";

            // 系统执行器
            Runtime rt = Runtime.getRuntime();

            // 导出数据库语句
            String cmd = "mysqldump -u" +
                    "root" +
                    " -p" +
                    "evil" +
                    " --set-charset=utf8 " +
                    "mealorder";

            Process child = rt.exec(cmd);
            InputStream in = child.getInputStream();
            InputStreamReader ir = new InputStreamReader(in, "utf-8");

            FileOutputStream fo = new FileOutputStream(filePath);
            OutputStreamWriter os = new OutputStreamWriter(fo, "utf-8");

            char[] temp = new char[1024000];
            int len;
            while ((len = ir.read(temp)) > 0)
            {
                os.write(temp, 0, len);
                os.flush();
            }

            System.out.println("备份成功：" + format.format(new Date()));
            in.close();
            ir.close();
            os.close();
            fo.close();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}
